package top.infopub.mgr.sys.service.impl;


import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.sys.dao.MenuDao;
import top.infopub.mgr.sys.service.MenuService;
import top.infopub.mgr.sys.service.PurviewService;
import top.infopub.mgr.sys.service.RolepurviewService;
import top.infopub.mgr.sys.vo.MenuVo;
import top.infopub.model.sys.Menu;


@Service
public class MenuServiceImpl extends GenericServiceImpl<Menu, String> implements MenuService {

    @Autowired
    private MenuDao menuDao;
    
    @Autowired
    private PurviewService purviewService;
    
    @Autowired
    private RolepurviewService rolepurviewService;

    @Override
    public GenericDao<Menu, String> getDao() {
        return menuDao;
    }

    public List<Menu> queryByUserId(String userId) {
        return this.menuDao.selectByUserId(userId);
    }

    @Override
    public boolean isExistName(Menu param) {
        return menuDao.isNameExist(param) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Menu menu, String id) {
        if (id == null) {// 如果id为空，则为添加
            // 先设置父节点不是叶子节点
            Menu menu1 = menuDao.selectByPrimaryKey(menu.getSparentId());
            if (menu1.getBisLeaf().equals("1")) {
                menu1.setBisLeaf("0");
                menuDao.updateByIdSelective(menu1);
            }
            // 设置节点
            menu.setBisLeaf("1");
            menu.setBisRoot("0");
            menu.setBisDisplay("1");
            menu.setDaddDate(new Date());
        }
        menuDao.insert(menu);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(String id) {
        Menu menu = menuDao.selectByPrimaryKey(id);
        menuDao.deleteByPrimaryKey(id);
        //删除菜单后，判断是否还有兄弟菜单，如没有，则更新父菜单不为父节点
        List<Menu> menus = menuDao.selectByParentId(menu.getSparentId());
        if(CollectionUtils.isEmpty(menus)){
            //设置父菜单不是父节点
            Menu menu1 = menuDao.selectByPrimaryKey(menu.getSparentId());
            if (menu1.getBisRoot().equals("1")) {
                menu1.setBisRoot("0");
                menuDao.updateByIdSelective(menu1);
            }
        }
    }

    @Override
    public List<MenuVo> queryNaviJsonByUser(String loginUserId) {
        // 查询用户的导航菜单
        List<Menu> menuList = menuDao.selectByUserId(loginUserId);
        // 存储vo
        List<MenuVo> voList = new LinkedList<>();
        // 返回值list
        List<MenuVo> jsonList = new LinkedList<>();
        // 用于转换VO
        MenuVo vo = null;
        Map<String, String> atts = null;
        List<MenuVo> children = null;
        for (Menu var : menuList) {
            vo = new MenuVo();
            // 设置 url attributes
            atts = new LinkedHashMap<String, String>();
            atts.put("url", var.getSmenuPath());
            vo.setAttributes(atts);
            vo.setId(var.getId());
            vo.setParentId(var.getSparentId());
            vo.setMenuCode(var.getSmenuNo());
            vo.setText(var.getSname());
            vo.setMenuUrl(var.getSmenuPath());
            // 菜单图标class
            vo.setIconCls(var.getSimagePath());
            vo.setBisRoot(var.getBisRoot());
            voList.add(vo);
        }
        // 根据easyUI Tree要求拼装 json
        for (MenuVo menu : voList) {
            // 一级菜单 parentId=-1
            if (("-1").equals(menu.getParentId())) {
                children = new LinkedList<>();
                // 导航菜单共两级（综合easyUI Tree），这里嵌套一次。
                for (MenuVo inner : voList) {
                    // 父id与外层一致id，则将inner添加为外层的children
                    if (inner.getParentId().equals(menu.getId())) {
                        List<MenuVo> secendchildren = new LinkedList<>();
                        if("1".equals(inner.getBisRoot())){//判断是否有三级菜单
                            for (MenuVo innerVo : voList) {
                                // 父id与外层一致id，则将inner添加为外层的children
                                if (innerVo.getParentId().equals(inner.getId())) {
                                    secendchildren.add(innerVo);
                                }
                                inner.setChildren(secendchildren);
                            }
                        }
                        children.add(inner);
                    }
                }
                menu.setChildren(children);
                jsonList.add(menu);
            }
        }
        return jsonList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAndDelPur(Menu menu) {
        List<String> purviews = purviewService.selectByParentId(menu.getSparentId());
        if(CollectionUtils.isNotEmpty(purviews)){
            String[] purIds = new String[purviews.size()];
            purviews.toArray(purIds);
            //删除角色对应权限码
            rolepurviewService.batchDeleteByPurIds(purIds);
            //删除权限码
            purviewService.batchDeleteByIds(purIds);
        }
        //先设置父菜单为父节点
        Menu menu1 = menuDao.selectByPrimaryKey(menu.getSparentId());
        if (menu1.getBisRoot().equals("0")) {
            menu1.setBisRoot("1");
            menuDao.updateByIdSelective(menu1);
        }
        menuDao.insert(menu);
    }
}